package com.swt.gap.controller;

import com.swt.gap.common.PageResult;
import com.swt.gap.common.RoleEnum;
import com.swt.gap.dao.SysRoleMapper;
import com.swt.gap.dao.SysUserMapper;
import com.swt.gap.model.entity.SysRole;
import com.swt.gap.model.vo.*;
import com.swt.gap.service.SysUserService;
import com.swt.gap.util.UserLoginUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 请填写说明
 *
 * @author
 */
@Api(tags = "101. 用户相关")
@RestController
@RequestMapping("/admin")
@Slf4j
public class SysUserController {

    private final SysUserService userService;
    private final SysRoleMapper sysRoleMapper;

    public SysUserController(SysUserService userService, SysRoleMapper sysRoleMapper) {
        this.userService = userService;
        this.sysRoleMapper = sysRoleMapper;
    }

    @PostMapping
    @ApiOperation(value = "1新增用户", notes = "1新增用户")
    @ApiImplicitParam(name = "userAddVO", dataType = "UserAddVO",paramType = "body", value = "用户信息")
    @ApiResponses({@ApiResponse(code = 201, message = "添加成功"),
                   @ApiResponse(code = 409, message = "已重名"),
                   @ApiResponse(code = 400, message = "非法请求")})
    public ResponseEntity addUser(@RequestBody UserAddVO userAddVO){
        if (!userService.hasAdminPerms()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("没有权限");
        }
        String userName = userAddVO.getUserName();
        if(StringUtils.isNotBlank(userName)){
            userName = userName.trim();
            if(userName.length() > 10){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名长度不能超过10");
            }
            userAddVO.setUserName(userName);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名不能为空");
        }
        Boolean isRepeat = userService.judgeName(userAddVO.getUserName(), null);
        if (isRepeat) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("用户名已存在");
        }
        if (userAddVO.getRoleId() == null || userAddVO.getRoleId() < 1) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("角色不能为空");
        }

        userService.addNewUser(userAddVO);
        return ResponseEntity.status(HttpStatus.CREATED).body("新增用户成功");
    }

//    @GetMapping("user-name")
//    @ApiOperation(value = "2.2判断用户名是否可用", notes = "2.2判断用户名是否可用，重复不可用")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userName", dataType = "String", value = "新增或修改的用户名"),
//            @ApiImplicitParam(name = "userId", dataType = "int", value = "编辑时传用户id，新增时没有")})
//    @ApiResponses({@ApiResponse(code = 200, message = "可用或不可用",response = Boolean.class)})
//    public ResponseEntity judgeName(@RequestParam String userName, @RequestParam(required = false) Integer userId){
//        return ResponseEntity.ok(userService.judgeName(userName, userId));
//    }


//    @PutMapping("user-name/{userId}")
//    @ApiOperation(value = "修改用户名", notes = "管理员修改用户名")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "userId", dataType = "int", value = "根据用户id修改用户名"),
//            @ApiImplicitParam(name = "userName", dataType = "String", value = "新用户名")})
//    @ApiResponses({@ApiResponse(code = 200, message = "修改成功"), @ApiResponse(code = 404, message = "修改失败")})
//    public ResponseEntity updateUserName(@PathVariable Integer userId, @RequestParam String userName){
//        int result = userService.updateName(userName, userId);
//        if(result == -1){
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("用户名已存在，修改失败");
//        }
//        if(result < 1){
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("修改失败");
//        }
//        return ResponseEntity.ok("修改成功");
//    }


    @PutMapping("/user/{userId}")
    @ApiOperation(value = "2编辑用户", notes = "2编辑用户，编辑姓名、所属机构、启用状态等，即使修改其中一个也需要附带其余信息")
    @ApiImplicitParams ({
            @ApiImplicitParam(name = "userId", dataType = "int",paramType = "path", value = "用户Id"),
            @ApiImplicitParam(name = "userEditVO", dataType = "UserEditVO",paramType = "body",
                    value = "注意：即使修改其中一个也需要附带其余信息")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "ok")})
    public ResponseEntity<String> updateUserRole(@PathVariable Integer userId, @RequestBody UserEditVO userEditVO){
        if (!userService.hasAdminPerms()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("没有权限");
        }
        userEditVO.setUserId(userId);
        userService.updateUser(userEditVO);
        return ResponseEntity.ok("编辑成功");
    }


    @DeleteMapping("/{userId}")
    @ApiOperation(value = "3删除用户", notes = "3删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", dataType = "int", paramType = "path", value = "根据用户id删除用户")})
    @ApiResponses({@ApiResponse(code = 200, message = "删除成功")})
    public ResponseEntity deleteUser(@PathVariable Integer userId){
        if (!userService.hasAdminPerms()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("没有权限");
        }
        // todo 删除用户要不要删除该用户上传或创建的任务
        userService.deleteUser(userId);
        return ResponseEntity.ok("删除成功");
    }


    @GetMapping
    @ApiOperation(value = "获取分页用户列表", notes = "4获取所有未删除用户，也可根据用户名和角色模糊查询用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", dataType = "int", paramType = "query", value = "获取的当前页码，默认从第一页开始"),
            @ApiImplicitParam(name = "pageSize", dataType = "int", paramType = "query", value = "每页的条数"),
            @ApiImplicitParam(name = "key", dataType = "String", paramType = "query", value = "输入的用户名"),
            @ApiImplicitParam(name = "roleId", dataType = "int", paramType = "query", value = "选择的角色Id")})
    @ApiResponses({@ApiResponse(code = 200, message = "用户列表",response = PageResult.class)})
    public ResponseEntity getUserListByPage(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "12") Integer pageSize,
                                            @RequestParam(value = "key", required = false) String key,
                                            @RequestParam(value = "roleId", required = false) Integer roleId){
        if (!userService.hasAdminPerms()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("此用户无权限");
        }
        return ResponseEntity.ok(userService.getUserListByPage(pageNum, pageSize, key, roleId));
    }

    @GetMapping("/user")
    @ApiOperation(value = "获取分页用户列表, v2", notes = "4获取用户列表 v2")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", dataType = "int", paramType = "query", value = "获取的当前页码，默认从第一页开始"),
            @ApiImplicitParam(name = "pageSize", dataType = "int", paramType = "query", value = "每页的条数"),
            @ApiImplicitParam(name = "keyword", dataType = "String", paramType = "query", value = "输入的用户名或姓名"),
            @ApiImplicitParam(name = "departmentId", dataType = "int", paramType = "query", value = "部门Id")})
    @ApiResponses({@ApiResponse(code = 200, message = "用户列表",response = PageResult.class)})
    public ResponseEntity listUser(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "12") Integer pageSize,
                                            @RequestParam(value = "keyword", required = false) String keyword,
                                            @RequestParam(value = "departmentId", required = false) Integer departmentId){
        if (!userService.hasAdminPerms()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("此用户无权限");
        }
        return ResponseEntity.ok(userService.listUser(pageNum, pageSize, keyword, departmentId));
    }

    @PutMapping("password/{userId}")
    @ApiOperation(value = "5重置密码", notes = "5重置密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", dataType = "int", paramType = "path", value = "用户id")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "重置成功")})
    public ResponseEntity resetPassword(@PathVariable Integer userId){
        Integer loginId = UserLoginUtils.getUserId();
        SysRole sysRole = sysRoleMapper.selectRoleByUserId(loginId);
        if (sysRole.getRoleId() != 1 && sysRole.getRoleId() != 3) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("没有权限");
        }
        userService.resetPassword(userId);
        return ResponseEntity.ok("重置密码成功");
    }



    @PutMapping("/user-password/{userId}")
    @ApiOperation(value = "6修改密码", notes = "6在个人中心修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", dataType = "int", paramType = "path", value = "用户id"),
            @ApiImplicitParam(name = "passwordUpdateVO", dataType = "PasswordUpdateVO", paramType = "body", value = "新旧密码")})
    @ApiResponses({@ApiResponse(code = 200, message = "修改成功"),
                   @ApiResponse(code = 404, message = "原始密码不正确"),
                   @ApiResponse(code = 400, message = "非法请求")})
    public ResponseEntity updateUserPassword(@PathVariable Integer userId, @RequestBody PasswordUpdateVO passwordUpdateVO){
        String oldPassword = passwordUpdateVO.getOldPassword();
        String newPassword1 = passwordUpdateVO.getNewPassword1();
        String newPassword2 = passwordUpdateVO.getNewPassword2();
        if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword1) && StringUtils.isNotBlank(newPassword2)) {
            Boolean result = userService.judgePassword(userId, oldPassword);
            if(!result){
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("原始密码不正确");
            }
            if (!newPassword1.equals(newPassword2)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("两次输入的新密码不一致");
            }
            if (!newPassword1.matches("^[a-z0-9A-Z]+$") || !newPassword2.matches("^[a-z0-9A-Z]+$") ) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("仅支持数字和大小写字母");
            }
            if(newPassword1.length() > 12 || newPassword1.length() < 6 ){
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("新密码为6~12位长度的字符");
            }
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("密码不能为空");
        }

        userService.updateUserPassword(userId, newPassword1);
        return ResponseEntity.ok("修改密码成功");
    }

    @GetMapping("token")
    @ApiOperation(value = "7根据token获取用户信息", notes = "7根据token获取用户信息")
    public ResponseEntity getUserByToken(){
        int userId = UserLoginUtils.getUser().getUserId();
        UserInfoVO userInfoVO = userService.getUserInfo(userId);
        return ResponseEntity.ok(userInfoVO);
    }


    /*@GetMapping("id-name")
    @ApiOperation(value = "8获取所有未删除用户id和用户名", notes = "8获取所有未删除用户id和用户名")
    @ApiResponses({@ApiResponse(code = 200, message = "ok",response = UserVO.class)})
    public ResponseEntity getUserVOs(){
        return ResponseEntity.ok(userService.getUsers());
    }*/

    @GetMapping("/department-user")
    @ApiOperation(value = "9 根据部门获取用户列表", notes = "9根据部门获取用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", dataType = "int", paramType = "query", value = "获取的当前页码，默认从第一页开始"),
            @ApiImplicitParam(name = "pageSize", dataType = "int", paramType = "query", value = "每页的条数"),
            @ApiImplicitParam(name = "keyword", dataType = "String", paramType = "query", value = "输入的用户名或者姓名"),
            @ApiImplicitParam(name = "departmentId", dataType = "int", paramType = "query", value = "选择的部门Id")})
    @ApiResponses({@ApiResponse(code = 200, message = "用户列表",response = PageResult.class)})
    public ResponseEntity<PageResult> listUserByDepartmentId(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                     @RequestParam(value = "keyword", required = false) String keyword,
                                     @RequestParam(value = "departmentId") Integer departmentId){
        return ResponseEntity.ok(userService.listUserByDepartmentId(pageNum, pageSize, keyword, departmentId));
    }


    @GetMapping("/user/access-role")
    @ApiOperation(value = "获取用户可用的下级角色", notes = "获取用户可用的下级角色")
    @ApiResponses({@ApiResponse(code = 200, message = "用户列表",response = SysRole.class, responseContainer = "List")})
    public ResponseEntity<List<SysRole>> listUserAccessRole(){
        return ResponseEntity.ok(userService.listUserAccessRole(UserLoginUtils.getUserId()));
    }

}
